package libnetdb.dm.assoc.util;
import java.io.*;

/**
 * This class provides a way to encode a <code>Serializable</code> object to byte array.
 * This class cannot be substantiated or inhirited.
 *
 * @author Cheng-Ru Lin
 * @version 1.0
 */

public final class SerializationCodec extends Exception {

    private SerializationCodec(){}

    /**
     * Enocodes the specified object to byte array.
     * @param obj the object to be encoded
     * @return byte array which can be decoded to the object
     */
    static public byte[] encode(Object obj){
        try{
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            oos.close();
            baos.close();
            return baos.toByteArray();
        }catch(IOException e){
            return null;
        }
    }

    /**
     * Decodes the specified byte array to an object.
     * @param buf the byte array to be decoded
     * @return the decoded object
     * @throws ClassNotFoundException if the <code>Class</code> of the decoded object
     *     cannot be found by the <code>SystemClassLoader</code>
     */
    static public Object decode(byte[] buf) throws ClassNotFoundException{
        try{
            ByteArrayInputStream bais = new ByteArrayInputStream(buf);
            ObjectInputStream ois = new ObjectInputStream(bais);
            Object obj = ois.readObject();
            ois.close();
            bais.close();
            return obj;
        }catch(IOException e){
            return null;
        }
    }
}